$(function () {
    // 通过new mui.PopPicker()初始化popPicker组件
    var picker = new mui.PopPicker({
        layer: 3
    });
    // 给picker对象添加数据
    picker.setData(cityData);
    // 显示picker
    $("#showCityPicker").on("tap", function () {
        picker.show(function (selectItems) {
            // console.log(selectItems);
            $('[name="address"]').val((selectItems[0] || {}).text + (selectItems[1] || {}).text + (selectItems[2] || {}).text);
        });
    });

    // 默认为添加收货地址
    var flag = true;

    // 看地址栏中是否有ID参数 如果有就是修改地址 否则就是添加地址
    if (getParamsByUrl(location.href, 'id')) {
        // 修改收获地址
        flag = false;
        $.ajax({
            url: ajaxUrl('queryAddress'),
            method: 'get',
            success: function (result) {
                for (var i = 0; i < result.length; i++) {
                    if (result[i].id == getParamsByUrl(location.href, 'id')) {
                        $('[name="address"]').val(result[i].address);
                        $('[name="addressDetail"]').val(result[i].addressDetail);
                        $('[name="recipients"]').val(result[i].recipients);
                        $('[name="postcode"]').val(result[i].postCode);
                    }
                }
            }
        });
    }


    $("#addAdress").on("tap", function () {
        var This = $(this);
        var url = ajaxUrl('addAddress');
        var data = {
            address: $.trim($('[name="address"]').val()),
            addressDetail: $.trim($('[name="addressDetail"]').val()),
            recipients: $.trim($('[name="recipients"]').val()),
            postcode: $.trim($('[name="postcode"]').val())
        }

        if (!flag) {
            data.id = getParamsByUrl(location.href, 'id');
        }

        if (!data.address) {
            mui.toast('请选择地址');
            return;
        }
        if (!data.addressDetail) {
            mui.toast('请输入详细地址');
            return;
        }
        if (!data.recipients) {
            mui.toast('请输入收货人');
            return;
        }
        if (!data.postcode) {
            mui.toast('请输入邮政编码');
            return;
        }
        $.ajax({
            url: (flag ? ajaxUrl('addAddress') : ajaxUrl('updateAddress')),
            type: 'post',
            data: data,
            beforeSend: function () {
                This.html('正在' + (flag ? '添加' : '修改') + '收货地址');
            },
            success: function (result) {
                if (result.success) {
                    mui.toast(flag ? "添加成功" : "修改成功")
                    setTimeout(function () {
                        location.href = "address.html";
                    }, 2000);
                } else {
                    mui.toast(result.message)
                }
                This.html(flag ? '添加' : '修改');
            }
        });
    })
})